import {Net, SendLogin} from "foundation";

export const waitingRegistry = new Map<String, ((err: Error|null)=>void)[]>();

async function login(net:Net, loginFail: (err: Error)=>void) {
  let ret= await Taro.login({});
  let err:Error;
  if (ret.errMsg) {
    err = new Error(ret.errMsg);
  } else {
    let err0 = await SendLogin('ts/wxappLogin/LoginByJscode', {jsCode:ret.code}, net);
    err = new Error(err0?.message);
  }
  if (err) {
    await Taro.showModal({content:`登录失败(${ret.errMsg})`});
  }

  let waiting = waitingRegistry.get(net.getPlugin().getName())!;
  for (let w of waiting) {
    w(err)
  }

  waitingRegistry.set(net.getPlugin().getName(), []);

  if (err) {
    loginFail(err)
  }
}

export function RegisterAutoLogin(net:Net, loginFail:(err: Error)=>void = err => {console.error(err)}) {
  waitingRegistry.set(net.getBaseUrl(), []);
  net.set401Delegate(net1 =>{
    login(net1, loginFail).then()
  })
}

export function UnRegisterAutoLogin(net:Net, net401delegate:(net:Net)=>void) {
  net.set401Delegate(net401delegate);
  waitingRegistry.delete(net.getBaseUrl());
}

